/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.MumuUser;
import service.MumuUserFacadeREST;
import utilities.ReadSmtp;
import utilities.settings;

/**
 *
 * @author andrew
 */
public class passwordRecoverServlet extends HttpServlet {

    @EJB
    private MumuUserFacadeREST userManager;
    
    private Session session;
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        final ReadSmtp readSmtp = new ReadSmtp(request);
        
        // riceve mail
        String email = request.getParameter("email");
        if(email != null){
        
        // controlla se nel db utenti esiste la mail corrispondente
        List<MumuUser> userList = userManager.findAll();
        
        int idUser = -1;
        String nameSurname = "";
                
        Iterator<MumuUser> userIt = userList.iterator();
        MumuUser tmpUser;
        while(userIt.hasNext()){
            tmpUser = userIt.next();
            if(tmpUser.getMail().equals(email)){
                idUser = tmpUser.getIdUser();
                nameSurname = tmpUser.getNameSurname();
                break;
            }
        }
        
        if(idUser != -1){
            // utente riconosciuto
            
            // generazione bundleID
            UUID bundleId = UUID.randomUUID();
            
            // setta bundleID nel campo dell'utente
            MumuUser user = userManager.find(idUser);
            user.setBundleID(bundleId.toString());
            userManager.edit(user);
            
            // invio mail
            System.out.println("8");
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            
            
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( email, "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
                message.setSubject("UniverseCreator: recupero password");
                String content = "Gentile " + nameSurname + ",<br/><br/>"
                        + "Questa mail ti &egrave; stata inviata perchè &egrave; stato richiesto il recupero della password.<br/>"
                        + "<br/>"
                        + "Cliccando nel seguente link potrai impostare la tua nuova password <br/>"
                        + "<br/><br/>"
                        // settings.getAddressServer()
                        + "<a href=https://localhost:8181/home.jsp?b="+bundleId.toString()+">Clicca per resettare la tua password</a>"
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
                
                PrintWriter o = response.getWriter();
                o.write("<p>Grazie <strong>"+ user.getNameSurname() +"</strong> una mail &egrave; stata inviata all'indirizzo specificato.</p>");
                o.flush();
                o.close();
                
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
        }else{
            String referrer = request.getHeader("referer");
            System.out.println(referrer);
            if(referrer.contains("home.jsp")){
                PrintWriter o = response.getWriter();
                o.write("<p>L'email inserita non &egrave; presente nel sistema, prova ad iscriverti!</p>");
                o.flush();
                o.close();
            } else {
                response.sendRedirect("/home.jsp");
            }
            // mail non presente nel sistema
        }
            
        } else {
            response.sendRedirect("/home.jsp");
        }
        
        
        
        
        
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // cerca bundleID se OK cambia la password e cancella bundle ID
        PrintWriter o = response.getWriter();
        // riceve bundleID
        String code = request.getParameter("code");
        String newPassword = request.getParameter("password");
        newPassword = getMD5(newPassword);
        
        List<MumuUser> userList = userManager.findAll();
        int idChecked = this.checkBundle(code, userList);
        
        if(idChecked != -1){
            MumuUser foundedUser = userList.get(idChecked);
            foundedUser.setPassword(newPassword);
            foundedUser.setBundleID("");
            userManager.edit(foundedUser);
            o.write("Congratulazioni <strong>"+ foundedUser.getNameSurname() + "</strong>, la tua password &egrave; appena stata cambiata!");
        } else {
            o.write("Siamo spiacenti, ma la password dell'utente &egrave; gi&agrave; stata recuperata.");
        }
        o.flush();
        o.close();
    }
    
    
    private int checkBundle(String code, List<MumuUser> userList){
        // cerca su DB se esiste un bundleID uguale
        
        Iterator<MumuUser> userIt = userList.iterator();
        
        MumuUser tmpUser;
        int i = 0;
        
        while(userIt.hasNext()){
            tmpUser = userIt.next();
            if(tmpUser.getBundleID() != null && tmpUser.getBundleID().equals(code))
                return i;
            i++;
        }
        return -1;
    }
    
    
    private static String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
